import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import request from '@/utils/request'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
  
  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const userRole = computed(() => userInfo.value.role || '')
  const laboratoryId = computed(() => userInfo.value.laboratoryId || null)
  
  // 登录
  const login = async (loginForm) => {
    try {
      const response = await request.post('/auth/login', loginForm)
      const { token: newToken, userInfo: userData } = response.data
      
      // 保存token和用户信息
      token.value = newToken
      userInfo.value = userData
      localStorage.setItem('token', newToken)
      localStorage.setItem('userInfo', JSON.stringify(userData))
      
      return response
    } catch (error) {
      throw error
    }
  }
  
  // 模拟登录（用于测试）
  const mockLogin = (role) => {
    const mockUsers = {
      admin: {
        id: 1,
        username: 'admin',
        role: 'ADMIN',
        name: '系统管理员',
        laboratoryId: null,
        laboratoryName: null
      },
      leader1: {
        id: 2,
        username: 'leader1',
        role: 'LEADER',
        name: '上级领导',
        laboratoryId: null,
        laboratoryName: null
      },
      lab_manager1: {
        id: 3,
        username: 'lab_manager1',
        role: 'LAB_MANAGER',
        name: '实验室管理员',
        laboratoryId: 1,
        laboratoryName: '计算机实验室A'
      }
    }
    
    const userData = mockUsers[role] || mockUsers.admin
    const mockToken = 'mock-token-' + Date.now()
    
    token.value = mockToken
    userInfo.value = userData
    localStorage.setItem('token', mockToken)
    localStorage.setItem('userInfo', JSON.stringify(userData))
    
    return { data: { token: mockToken, ...userData } }
  }
  
  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const response = await request.get('/auth/me')
      userInfo.value = response.data
      localStorage.setItem('userInfo', JSON.stringify(response.data))
      return response
    } catch (error) {
      throw error
    }
  }
  
  // 登出
  const logout = () => {
    token.value = ''
    userInfo.value = {}
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }
  
  // 检查权限
  const hasRole = (role) => {
    return userRole.value === role
  }
  
  const hasAnyRole = (roles) => {
    return roles.includes(userRole.value)
  }
  
  return {
    token,
    userInfo,
    isLoggedIn,
    userRole,
    laboratoryId,
    login,
    mockLogin,
    getUserInfo,
    logout,
    hasRole,
    hasAnyRole
  }
})
